package com.jingdianjichi.gateway.auth.exception;

import cn.dev33.satoken.exception.SaTokenException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingdianjichi.gateway.auth.entity.Result;
import org.apache.logging.log4j.message.Message;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

/**
 * ClassName:SaTokenExceptionHandler
 * Package:com.jingdianjichi.gateway.auth.exception
 * Description:
 *
 * @Author fst
 * @Create 2024/10/9 15:56
 * @Version 1.0
 */

@RestControllerAdvice
public class SaTokenExceptionHandler implements ErrorWebExceptionHandler
{
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        ServerHttpRequest request = serverWebExchange.getRequest();
        ServerHttpResponse response = serverWebExchange.getResponse();

        int code=200;
        String message=null;
        if(throwable instanceof SaTokenException)
        {
            code=401;
            message="用户无权限";
        }
        else
        {
            code=500;
            message="服务器繁忙";
        }

        Result result=Result.fail(code,message);

        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        return response.writeWith(Mono.fromSupplier(()->
        {
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            byte[] bytes = null;
            try {

                bytes = objectMapper.writeValueAsBytes(result);
            } catch (JsonProcessingException e) {

                e.printStackTrace();
            }
            return dataBufferFactory.wrap(bytes);
        }));
    }
}
